<?php

use Carbon\Carbon;

/* * ****************************************************************************
 * controllers\MaintenanceController
 * 
 * author  Laureta Xhaferaj
 * email   laureta@first.al
 * 
 * @function index
 * @function create
 * @function store
 * @function show
 * @function edit
 * @function update
 * @function destroy
 * @function vehicle_maintenance
 * @function maintenance_history
 * @function maintenance_print
 * 
 * *************************************************************************** */

class MaintenanceController extends \BaseController {

    public function __construct() {
        $this->beforeFilter('auth', array('only' => array('index')));
    }

    /**
     * Display table of maintenaces info.
     *
     * @return array
     */
    public function index($id) {
        $maintenance = DB::select('SELECT m.*,m.id as maint_id, u.username,
            u.first_name, c.milage, p.id, p.process, s.name
                      FROM maintenances as m
                        LEFT JOIN users AS u
                          ON u.id = m.user_id
                        LEFT JOIN cars AS c
                          ON c.id = m.car_id
                        LEFT JOIN processes as p
                          ON p.id = m.process_id
                        LEFT JOIN services as s
                          ON s.id = m.service_id
                        INNER JOIN (SELECT id from maintenances as m3
                                     WHERE maintenance_date = 
                                    (SELECT MAX(m2.maintenance_date) 
                                     FROM maintenances m2 WHERE m2.car_id = m3.car_id 
                                     AND m2.process_id = m3.process_id)) AS l ON l.id = m.id
                        WHERE m.car_id = "' . $id . '"
                      Group by m.car_id, m.process_id');

        $current_date = Carbon::now();
        $processes = DB::select('select * from processes');
        $car_process = DB::select('select process_id from maintenances '
                        . 'where car_id ="' . $id . '" group by process_id');
        $result = array();
        foreach ($car_process as $key => $value) {
            $result[] = $value->process_id;
        }
        return View::make('pages.maintenance', array(
                    'maintenance' => $maintenance,
                    'car_id' => $id,
                    'current_date' => $current_date,
                    'processes' => $processes,
                    'car_process' => $result,
        ));
    }

    /**
     * The form that  creates a new maintenace for a specific vehicle.
     *
     * @return array
     */
    public function create($id) {
        $process = DB::table('processes')->orderBy('process', 'asc')
                        ->distinct()->lists('process', 'id');
        array_walk($process, function(&$value, $key) {
            $value = Lang::get('processes.' . $value);
        });
        $services = DB::table('services')->orderBy('name', 'asc')
                        ->distinct()->lists('name', 'id');
        $data = DB::select('select p.km_due, p.month_due  from maintenances as m '
                        . 'left join processes as p '
                        . 'on  p.id = m.process_id ');
        $km_due = isset($data[0]->km_due) ? $data[0]->km_due : '';
        $month_due = isset($data[0]->month_due) ? $data[0]->month_due : '';
        $currencies = array(
            'EUR' => 'EUR',
            'LEK' => 'LEK',
        );
        return View::make('pages.maintenance_create', array(
                    'process' => $process,
                    'car_id' => $id,
                    'km_due' => $km_due,
                    'month_due' => $month_due,
                    'services' => $services,
                    'currencies' => $currencies
        ));
    }

    /**
     * The form that stores new maintenance for a vehicle.
     *
     * @return Response
     */
    public function store() {
        Input::flash();
        $data = [
            "errors" => null
        ];
        $attributes = array(
            'process' => Lang::get('messages.process'),
            'maintenance_date' => Lang::get('messages.maintenance_date'),
            'price' => Lang::get('messages.price'),
            'service' => Lang::get('messages.service'),
            'type' => Lang::get('messages.type_maintenance'),
            'kasko' => Lang::get('messages.kasko'),
        );
        $rules = array(
            "process" => "required",
            "maintenance_date" => "required",
            "price" => "required",
            "service" => "required",
            "type" => "required",
        );
        $validation = Validator::make(Input::all(), $rules, array(), $attributes);
        $id = Input::get('car_id');
        $milage = DB::select('select milage from cars where id=?', array($id));
        if ($validation->passes()) {
            $data = new Maintenance;
            $data->car_id = $id;
            $data->process_id = Input::get('process');
            $data->maintenance_date = Input::get('maintenance_date');
            $data->descr = Input::get('description');
            $data->price = Input::get('price');
            $data->km_due = Input::get('km_due');
            $data->month_due = Input::get('month_due');
            $data->comment = Input::get('comment');
            $data->service_id = Input::get('service');
            $data->type = Input::get('type');
            $data->nr_invoice = Input::get('nr_invoice');
            $data->currency = Input::get('currency');
            $data->maint_milage = $milage[0]->milage;
            $data->user_id = Auth::user()->id;
            $data->save();
//save into maint insert hisotry
            $maint_data = new MaintInsert;
            $maint_data->car_id = $id;
            $maint_data->process_id = Input::get('process');
            $maint_data->maintenance_date = Input::get('maintenance_date');
            $maint_data->descr = Input::get('description');
            $maint_data->price = Input::get('price');
            $maint_data->km_due = Input::get('km_due');
            $maint_data->month_due = Input::get('month_due');
            $maint_data->comment = Input::get('comment');
            $maint_data->service_id = Input::get('service');
            $maint_data->type = Input::get('type');
            $maint_data->nr_invoice = Input::get('nr_invoice');
            $maint_data->currency = Input::get('currency');
            $maint_data->maint_milage = $milage[0]->milage;
            $maint_data->user_id = Auth::user()->id;
            $maint_data->save();
// redirect
            return Response::json(["redirect_to" => "../../maintenance/$id"]);
        } else {
            if (Request::ajax()) {
                $response_values = array(
                    'validation_failed' => 1,
                    'errors' => $validation->errors()->toArray(),
                );
                return Response::json($response_values);
            }
        }
    }

    /**
     * Display a table with general data about all vehicles maintenance.
     *
     * @return array
     */
    public function vehicle_maintenance() {
        $vehicle_maintenance = DB::select('SELECT m. * , u.username, c.Model, 
            c.Make, c.License, c.Milage, COUNT( m.process_id ) AS count, 
            MAX(m.maintenance_date) as max_date
                    FROM maintenances AS m 
                    LEFT JOIN
                         users AS u
                         ON u.id = m.user_id 
                    LEFT JOIN
                         cars AS c
                         ON c.id = m.car_id
                    GROUP BY car_id');
        $current_date = Carbon::now();
        return View::make('pages.vehicle_maintenance', array(
                    'vehicle_maintenance' => $vehicle_maintenance,
        ));
    }

    /**
     * Display maintenance history of changes.
     *
     * @return array
     */
    public function maintenance_history($id) {
        $maintenance = DB::select('select m.*, u.username, c.milage, p.*,'
                        . ' s.name from maintenances as m '
                        . 'left join users as u on u.id=m.user_id '
                        . 'left join cars as c on c.id = m.car_id '
                        . 'left join processes as p on p.id=m.process_id '
                        . 'left join services as s on s.id=m.service_id '
                        . 'where car_id =?', array($id));

        $month_due = isset($maintenance[0]->month_due) ? $maintenance[0]->month_due : '';
        $maintenance_date = isset($maintenance[0]->maintenance_date) ? $maintenance[0]->maintenance_date : '';
        $next_date = Carbon::instance(new DateTime($maintenance_date))->addMonths($month_due);
        return View::make('pages.maintenance_history', array(
                    'maintenance' => $maintenance,
                    'next_date' => $next_date,
        ));
    }

    /**
     * Display a report of maintenances.
     *
     * @return array
     */
    public function maintenance_print() {
        $maintenance = DB::select('SELECT m.*, c.milage,c.Make,c.License,p.id, p.process
                      FROM maintenances as m                     
                        LEFT JOIN cars AS c
                          ON c.id = m.car_id
                        LEFT JOIN processes as p
                          ON p.id = m.process_id
                        INNER JOIN (SELECT id from maintenances as m3
                                     WHERE maintenance_date = 
                                    (SELECT MAX(m2.maintenance_date) 
                                     FROM maintenances m2 WHERE m2.car_id = m3.car_id 
                                     AND m2.process_id = m3.process_id)) AS l ON l.id = m.id
                      Group by m.car_id, m.process_id');
        $current_date = Carbon::now();
        return View::make('pages.maintenance_report', array(
                    'maintenance' => $maintenance,
                    'current_date' => $current_date
        ));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id) {
//
    }

    /**
     * Edit a specific maintenance for a speciific vehicle.
     *
     * @param  int  $id
     * @return array
     */
    public function edit($id) {
        $values = DB::select('select m.*,m.id as maint_id,s.*,p.* '
                        . 'from maintenances as m '
                        . 'left join services as s '
                        . 'on s.id=m.service_id '
                        . 'left join processes as p '
                        . 'on p.id=m.process_id '
                        . 'where m.id = ?', array($id));
        $processes = DB::table('processes')->orderBy('process', 'asc')
                        ->distinct()->lists('process', 'id');
        array_walk($processes, function(&$value, $key) {
            $value = Lang::get('processes.' . $value);
        });
        $services = DB::table('services')->orderBy('name', 'asc')
                        ->distinct()->lists('name', 'id');
        $currencies = array(
             'EUR' => 'EUR',
            'LEK' => 'LEK',
        );
        return View::make('pages.maintenance_edit', array(
                    'values' => $values,
                    'processes' => $processes,
                    'id' => $id,
                    'services' => $services,
                    'currencies' => $currencies
        ));
    }

    /**
     * The form that updates maintenances data.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id) {
        Input::flash();
        $data = [
            "errors" => null
        ];
        $attributes = array(
            'process' => Lang::get('messages.process'),
            'price' => Lang::get('messages.price'),
            'maintenance_date' => Lang::get('messages.maintenance_date'),
            //'month_due' => Lang::get('messages.month_due'),
            'service' => Lang::get('messages.service'),
            'type' => Lang::get('messages.type'),
        );
        $rules = array(
            "process" => "required",
            "price" => "required",
            "maintenance_date" => "required",
            //"month_due" => "required",
            "service" => "required",
            "type" => "required",
        );
        $validation = Validator::make(Input::all(), $rules, array(), $attributes);
        $car_id = DB::select('select car_id from maintenances where id=?', array($id));
        $car = $car_id[0]->car_id;
        if ($validation->passes()) {
            $maintenance = Maintenance::find($id);
            $maintenance->process_id = Input::get('process');
            $maintenance->descr = Input::get('description');
            $maintenance->price = Input::get('price');
            $maintenance->maintenance_date = Input::get('maintenance_date');
            $maintenance->km_due = Input::get('km_due');
            $maintenance->month_due = Input::get('month_due');
            $maintenance->service_id = Input::get('service');
            $maintenance->type = Input::get('type');
            $maintenance->nr_invoice = Input::get('nr_invoice');
            $maintenance->currency = Input::get('currency');
            $maintenance->comment = Input::get('comment');
            $maintenance->save();
            return Response::json(["redirect_to" => "../../maintenance/" . $car]);
        } else {
            if (Request::ajax()) {
                $response_values = array(
                    'validation_failed' => 1,
                    'errors' => $validation->errors()->toArray(),
                );
                return Response::json($response_values);
            } else {
                echo 'error';
            }
        }
    }

    public function processes() {
        $data = DB::select('select * from processes');
        return View::make('pages.processes', array(
                    'data' => $data,
        ));
    }

    public function create_processes() {
        return View::make('pages.processes_create');
    }

    public function store_processes() {
        Input::flash();
        $data = [
            "errors" => null
        ];
        $attributes = array(
            'process' => Lang::get('messages.process'),
        );
        $rules = array(
            "process" => "required",
        );
        $validation = Validator::make(Input::all(), $rules, array(), $attributes);
        if ($validation->passes()) {
            $data = new Process;
            $data->process = Input::get('process');
            $data->km_due = Input::get('km_due');
            $data->month_due = Input::get('month_due');
            $data->save();

            $process = new ProcessesInsert;
            $process->process = Input::get('process');
            $process->km_due = Input::get('km_due');
            $process->month_due = Input::get('month_due');
            $process->user_id = Auth::user()->id;
            $process->save();
            //redirect
            return Response::json(["redirect_to" => "processes"]);
        } else {
            if (Request::ajax()) {
                $response_values = array(
                    'validation_failed' => 1,
                    'errors' => $validation->errors()->toArray(),
                );
                return Response::json($response_values);
            }
        }
    }

    public function destroy_processes($id) {
        $process = DB::select('select * from processes where id=?', array($id));
        $repair = Process::find($id);
        $data = New ProcessesDelete();

        $data->process = $process[0]->process;
        $data->km_due = $process[0]->km_due;
        $data->month_due = $process[0]->month_due;
        $data->user_id = Auth::user()->id;
        $data->save();
 
        $repair->delete();
        return Redirect::to('processes');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id) {
//
    }

}
